<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@page import="org.json.JSONObject"%>
<%@page import="java.util.List"%>
<%@page import="java.util.ArrayList"%>
<%@ page language="java" import="java.util.*"%>
<%@page language="java"  import="java.io.File"  pageEncoding="utf-8"%>
<%@page import="com.szboanda.platform.common.utils.StringUtils"%>
<%@page import="com.szboanda.platform.common.utils.Toolkit"%>
<%@page import="com.zhuozhengsoft.pageoffice.PageOfficeCtrl"%>
<%@page import="com.zhuozhengsoft.pageoffice.OpenModeType"%>
<%@page import="com.zhuozhengsoft.pageoffice.wordwriter.WordDocument"%>
<%@page import="com.zhuozhengsoft.pageoffice.PDFCtrl"%>
<%@page import="com.szboanda.platform.v3.util.io.FileUtils"%>
<%@page import="java.net.URLDecoder"%>
<%@page import="com.szboanda.platform.common.component.pageoffice.helper.PageofficeHelper"%>
<%@ page import="com.szboanda.platform.v3.util.helper.ActionHelper" %>
<%@ page import="java.text.SimpleDateFormat" %>
<%@taglib uri="http://java.pageoffice.cn" prefix="po" %>
<%@ include file="bindingDataRegion2.jsp" %>
<style>
	.thmb{
		margin-left: 5px;
		background:#9acfea;
	}

</style>

<%
	String ctx = request.getContextPath();
	//业务序号
	String wjid = (String)request.getAttribute("wjid") ;
	String wjlx = (String)request.getAttribute("wjlx") ;
	//模版id
	String templateId = request.getParameter("templateId");
	String ssoParams = request.getParameter("ssoParams");
	//业务数据id
	String ywsjId = request.getParameter("ywsjId");
	String beanName = request.getParameter("beanName");
	String beanParams = request.getParameter("beanParams");
	//用户操作文档的模式类型  1代表docReadOnly，2代表docNormalEdit，3代表docRevisionOnly
	//4代表docAdmin, 5代表xlsReadOnly, 6代表xlsNormalEdit
	//暂不支持：7代表docHandwritingOnly，8代表docSubmitForm，9代表xlsSubmitForm
	String modeType = request.getParameter("modeType");
	//是否显示控件的标题栏 是：true 否：false
	String showTitlebar = request.getParameter("showTitlebar");
	//显示的标题内容
	String title = (String)request.getSession().getAttribute("title");
	//是否显示菜单栏   是：true 否：false
	String  showMenubar = request.getParameter("showMenubar");
	//是否显示自定义工具栏 是：true 否：false
	String  showCustomToolbar = request.getParameter("showCustomToolbar");
	//是否显示Office工具栏 是：true 否：false
	String  showOfficeToolbar = request.getParameter("showOfficeToolbar");
	//是否显示保存按钮  是：true 否：false
	String showSaveBtn = request.getParameter("showSaveBtn");
	//保存的同时是否修订  是：true 否：false
	String saveWithRevision = request.getParameter("saveWithRevision");
	//是否显示签名按钮  是：true 否：false
	String showSignBtn = request.getParameter("showSignBtn");
	//是否显示盖章按钮 是：true 否：false
	String showSealBtn = request.getParameter("showSealBtn");
	//是否显示修订痕迹 是：true 否：false
	String showRevisionBtn = request.getParameter("showRevisionBtn");
	//是否接受修订 是：true 否：false
	String showAcceptRevisionBtn = request.getParameter("showAcceptRevisionBtn");
	//是否全屏显示 是：true 否：false
	String showFullScreenBtn = request.getParameter("showFullScreenBtn");
	//是否显示打印 是：true 否：false
	String showPrintDlg = request.getParameter("showPrintDlg");
	//是否显示历史批文 是：true 否：false
	String historicalDocuments = request.getParameter("historicalDocuments");
	//是否显示历史版本 是：true 否：false
	String showHistory = request.getParameter("showHistory");
	//是否显示另存为 是：true 否：false
	String saveAsDoc = request.getParameter("saveAsDoc");
	//是否允许复制、粘贴的功能 是：true 否：false
	String allowCopy = request.getParameter("allowCopy");
	//标准语句
	String buttonKeys = request.getParameter("buttonKeys");
	//签名图片宽度
	String signWidth = request.getParameter("signWidth");
	//用户自定义按钮
	String userDefineBtns =  request.getParameter("userDefineBtns");
	//参数
	String parameter =  request.getAttribute("parameter") == null ? "" : request.getAttribute("parameter").toString();

	if(!StringUtils.isEmpty(signWidth)){
		signWidth = Double.valueOf(signWidth) <= 0 ? "" : signWidth;
	}
	//签名图片高度
	String signHeight = request.getParameter("signHeight");
	if(!StringUtils.isEmpty(signHeight)){
		signHeight = Double.valueOf(signHeight) <= 0 ? "" : signHeight;
	}
	//查看文件标示，1：查看；0：不能被查看；
	String viewFlag = "0";
	//提示信息
	String msg = "";
	//pageoffice标签id
	String tagId = "pageOfficeCtrl";
	//根据类型不同，加载不同的组件
	List<String> sripts = new ArrayList<String>();



	//是否需要在打开后保存一次
	boolean isOpenedSave = false;

	if(StringUtils.isNotEmpty(wjid) && StringUtils.isNotEmpty(wjlx)){
		if(StringUtils.isNotEmpty(wjlx)){
			if("doc".equalsIgnoreCase(wjlx) || "docx".equalsIgnoreCase(wjlx) || "xls".equalsIgnoreCase(wjlx) || "xlsx".equalsIgnoreCase(wjlx)){
				PageOfficeCtrl ctrl = new PageOfficeCtrl(request);
				if("true".equals(showSaveBtn)){
					ctrl.addCustomToolButton("保存", "Save()", 1);
				}
				if("true".equals(showSignBtn)){
					ctrl.addCustomToolButton("签名", "InsertSign()", 2);
				}
				if("true".equals(showSealBtn)){
					ctrl.addCustomToolButton("盖章", "InsertSeal()", 2);
				}

				if("3".equals(modeType) || "true".equals(showRevisionBtn)){
					ctrl.addCustomToolButton("显示/隐藏修订痕迹", "displayRevision()", 0);
				}
				if("3".equals(modeType)){

					ctrl.addCustomToolButton("公文套红", "showTemplateDiv()", 9);
				}
				if("3".equals(modeType) || "true".equals(showAcceptRevisionBtn)){
					ctrl.addCustomToolButton("接受所有修订", "acceptRevision()", 5);
				}

				if (StringUtils.isNotEmpty(userDefineBtns)) {
					String baseKey = "bd.sys.platform.config.systemConfig.file.";
					String[] btnConfigs = userDefineBtns.split(";");
					for(String btnkey : btnConfigs){
						String btnConfig = Toolkit.getConfigValue(baseKey + btnkey);
						if (StringUtils.isNotEmpty(btnConfig)) {
							JSONObject cfg = new JSONObject(btnConfig);
							if (null != cfg.getString("scriptUrl") && !"filepreview".equals(cfg.getString("scriptUrl"))){
								if (!sripts.contains(cfg.getString("scriptUrl"))) {
									sripts.add(cfg.getString("scriptUrl"));
								}
							}
							String ftnName = cfg.getString("funtionName");
							try{
								if (StringUtils.isNotEmpty(cfg.getString("param"))) {
									ftnName = ftnName.replace("param", cfg.getString("param"));
								}
							} catch(Exception e){
							}
							ctrl.addCustomToolButton(cfg.getString("name"), ftnName, 5);
						}

					}
				}


				if(!"false".equals(showPrintDlg)){
					ctrl.addCustomToolButton("打印", "ShowPrintDlg()", 6);
				}
				if(!"false".equals(saveAsDoc)){
					ctrl.addCustomToolButton("另存为", "saveAsDoc()", 6);
				}
				if ("false".equals(allowCopy)) {//拷贝
					ctrl.setAllowCopy(false);
				}
				if(!"false".equals(showFullScreenBtn)){
					ctrl.addCustomToolButton("全屏切换", "SwitchFullScreen()", 4);
				}
				if("true".equals(showTitlebar)){
					ctrl.setCaption(title);
				}else{
					ctrl.setTitlebar(false);
				}
				if("false".equals(showMenubar)){
					ctrl.setMenubar(false);
				}
				if("false".equals(showOfficeToolbar)){
					ctrl.setOfficeToolbars(false);
				}
				if("false".equals(showCustomToolbar)){
					ctrl.setCustomToolbar(false);
				}
				//文档打开完毕时执行
				ctrl.setJsFunction_AfterDocumentOpened("AfterDocumentOpened");
				ctrl.setJsFunction_AfterDocumentSaved ("AfterDocumentSaved");
				OpenModeType openModeType = OpenModeType.docReadOnly;
				if("doc".equalsIgnoreCase(wjlx) || "docx".equalsIgnoreCase(wjlx)){
					if("1".equals(modeType)){
						openModeType = OpenModeType.docReadOnly;
					}else if("2".equals(modeType)){
						openModeType = OpenModeType.docNormalEdit;
					}else if("3".equals(modeType)){
						openModeType = OpenModeType.docRevisionOnly;
					}else if("4".equals(modeType)){
						openModeType = OpenModeType.docAdmin;
					} else {
						openModeType = OpenModeType.docReadOnly;
					}
				}else if("xls".equalsIgnoreCase(wjlx) || "xlsx".equalsIgnoreCase(wjlx)){
					if("6".equals(modeType)){
						openModeType = OpenModeType.xlsNormalEdit;
					}else if("5".equals(modeType)){
						openModeType = OpenModeType.xlsReadOnly;
					} else {
						openModeType = OpenModeType.xlsReadOnly;
					}
				}
				String savePath = request.getContextPath()+"/platform/common/pageofficecontroller/updateofficefile";
				/*if (StringUtils.isNotEmpty(beanName)) {
					PageofficeHelper helper = new PageofficeHelper();
					WordDocument docWriter = helper.initDocument(ywsjId, beanName, beanParams);
					ctrl.setWriter(docWriter);
					//提前保存一次
					isOpenedSave = true;
				}*/



				//String appid = request.getParameter("appid");//模板主键 T_WDSTORE
				//TWdstore wd=getWdstore(appid,"GWLX",null);
				String thPath = request.getParameter("thPath");
				if(StringUtils.isNotEmpty(thPath)){
					WordDocument doc = new WordDocument();
					DynaBean bean = getFwJbxx(ywsjId);//发文基本信息主键 t_oa_gwgl_fwdjjbxx
					String uploadPath = Toolkit.getConfigValue("bd.sys.platform.config.systemConfig.file.storeLocation");//获取文件上传路径
					String openFile = uploadPath+BeanUtils.getString(bean, "MLSY");
					openFile = openFile.replaceAll("\\/", "\\\\");
					String fileName = FileUtils.parseFileName(thPath);
					String newThmbPath = thPath.substring(0,thPath.lastIndexOf("/"))+"/temp/"+fileName;
					//复制一份套红模板到临时目录
					String realpath = this.getServletContext().getRealPath("/");
					FileUtils.copyFile(realpath+thPath,realpath+newThmbPath);

					DataRegion region = doc.openDataRegion("PO_WORDZW");//绑定正文
					region.setValue("[word]"+openFile+"[/word]");

					//设置正文字体开始,殷方磅2018-08-06
					Font font = region.getFont();
					font.setName("仿宋_GB2312");
					font.setSize(new Float(15).floatValue());
					//设置正文字体结束,殷方磅2018-08-06


					doc.openDataRegion("PO_WH").setValue(BeanUtils.getString(bean, "WH"));//绑定文号
					String jjcd = BeanUtils.getString(bean, "JJCD");
					doc.openDataRegion("PO_JJCD").setValue("TJ".equals(jjcd)?"特　急":"");//绑定紧急程度
					String qfr = BeanUtils.getString(bean, "QFR");
					String qfrName = regionValPplx(qfr,null,"YHBHQYHMC");
					doc.openDataRegion("PO_QFR").setValue(qfrName);//绑定签发人
					doc.openDataRegion("PO_BT").setValue(BeanUtils.getString(bean, "BT"));//绑定标题
					doc.openDataRegion("PO_ZS").setValue(BeanUtils.getString(bean, "ZS"));//绑定主送
					//doc.openDataRegion("PO_FJ").setValue(BeanUtils.getString(bean, "WJMC"));//绑定附件
					String cs=BeanUtils.getString(bean, "CS");
					doc.openDataRegion("PO_CS").setValue(cs);//绑定抄送
					if(StringUtils.isEmpty(cs)){
						doc.openDataRegion("PO_HCS").setValue("");
					}
					String curDate = DateUtils.simpleDateFormat(new Date(), "yyyy年M月d日");
					doc.openDataRegion("PO_THRQ").setValue(curDate);//绑定印发日期
					String bwbh = BeanUtils.getString(bean, "BWBH");
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy年M月d日");
					//根据办文编号在lsbz表中查询最后一个领导同意的时间
					//	DynaBean bean1 = getTHRQ(bwbh);
					//		String thDate = regionValPplx(BeanUtils.getString(bean1, "JSSJ"),null,"RQZH");
					doc.openDataRegion("PO_NGRQ").setValue(sdf.format(bean.get("NGSJ")));//绑定印发日期

					ctrl.setWriter(doc);
					openFile = ctx+newThmbPath;

				/*	//第一次创建时插入书签内容，将dataRegionJson传值内容绑定到文档书签中
					String dataRegionJson = (String)session.getAttribute("dataRegionJson");
					if(StringUtils.isNotEmpty(dataRegionJson)){
						//在线起草时，文档大小如果是空的，说明文档未保存过,则允许插入书签
						boolean isCanInsert= StringUtils.isEmpty(wd.getWddx())?true:false;
						if(isCanInsert){
							ctrl.setWriter(bindingDataRegion(dataRegionJson));
						}
					}*/
					ctrl.setSaveFilePage(savePath);
					ctrl.setServerPage(request.getContextPath()+"/poserver.do"); //此行必须
					ctrl.webOpen(openFile, openModeType, ActionHelper.getShareName());
					ctrl.setTagId(tagId); //此行必须
					viewFlag = "1";

				}else{
					ctrl.setSaveFilePage(savePath);
					ctrl.setServerPage(request.getContextPath()+"/poserver.do"); //此行必须
					PageofficeHelper.webOpen(ctrl, openModeType, request);
					//ctrl.webOpen(request.getContextPath()+"/Openstream.jsp?id=1", OpenModeType.docNormalEdit, "张三");
					ctrl.setTagId(tagId); //此行必须
					viewFlag = "1";
				}


			}else if("pdf".equalsIgnoreCase(wjlx)){
				PDFCtrl ctrl = new PDFCtrl(request);
				ctrl.setServerPage(request.getContextPath()+"/poserver.zz"); //此行必须
				PageofficeHelper.webOpen(ctrl, request);
				ctrl.setTagId(tagId); //此行必须
				viewFlag = "1";
			}else{
				msg = "您预览的文件类型暂时不支持，目前只支持doc、xls、docx、xlsx、pdf格式的文件！";
			}
		}else{
			msg = "您预览的文件类型错误，目前只支持doc、xls、docx、xlsx、pdf格式的文件！";
		}
	}else{
		msg = "您预览的文件不存在！";
	}


	request.setAttribute("wjid",wjid);
	request.setAttribute("viewFlag",viewFlag);
	request.setAttribute("msg",msg);
	request.setAttribute("doctype",wjlx);
	request.setAttribute("pageOfficeCtrl", tagId);
	request.setAttribute("signWidth", signWidth);
	request.setAttribute("signHeight", signHeight);






%>
<script type="text/javascript">
    var pageOfficeCtrl = '${pageOfficeCtrl}';
    var signatureId ='${signatureId}';
    var doctype ='${doctype}';
    var wjid = '${wjid}';
    var ywsjId = '${ywsjId}';
    var templateId = '<%=templateId%>';
    var isOpenedSave = <%=isOpenedSave%>
    var saveWithRevision = '<%=saveWithRevision%>';
    var webRoot = '<%=request.getContextPath()%>';
    var ssoParams = '<%=ssoParams%>';
    //套红功能
    function showTemplateDiv(){
        if($("#thmbDiv").css("display")=="none"){
            $("#thmbDiv").show();
        }else{
            $("#thmbDiv").hide();
        }
    }
</script>
<script type="text/javascript" src="<%=request.getContextPath()%>/resources/component/ztree/js/jquery-1.4.4.min.js?v=${sysversion}"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/resources/platform/maintain/demo/pageoffice1.js"></script>



<div id="thmbDiv" style="height:50px;display: none">
<c:forEach items="${gwlxList}" var="item">
	<%--<a class="thmb" lxxh="${item.LXMC}" onclick="taohong('${item.wdlj}','${item.XH}')" style="text-align:center;" title="${item.LXMC}" >
	${item.LXMC}
	</a>--%>
	<button lxxh="${item.LXMC}" class="thmb" onclick="taohong('${item.wdlj}','${item.XH}')" style="text-align:center;" title="${item.LXMC}">
			${item.LXMC}
	</button>
</c:forEach>
</div>

<body style="margin: 0px;overflow: hidden;" onload="testInstall()">

<form action="">
	<input type="hidden" id="ywsjId" name="ywsjId" value="${wjlx}"/>
	<input type="hidden" id="ywsjId" name="ywsjId" value="<%=ywsjId%>"/>
	<input type="hidden" id="beanName" name="beanName" value="<%=(beanName!=null?beanName:"")%>"/>
	<input type="hidden" id="beanParams" name="beanParams" value='<%=(beanParams!=null?beanParams:"")%>'/>
	<input type="hidden" id="wjid" name="wjid" value="<%=wjid%>"/>
	<input type="hidden" id="BACK_REVISIONS" name="BACK_REVISIONS" value="">
	<input type="hidden" id="REVISIONS_DESC" name="REVISIONS_DESC" value="">

	<%
		if ("1".equals(viewFlag)) {
			if ("pdf".equalsIgnoreCase(wjlx)) {
	%>
	<div id="docDisplayDiv" style="width: auto;">
		<po:PDFCtrl id="${pageOfficeCtrl}"></po:PDFCtrl>
	</div>
	<%
	} else {
	%>
	<div id="docDisplayDiv" style="width: auto;">
		<po:PageOfficeCtrl id="${pageOfficeCtrl}"/>
	</div>
	<%
		}
	} else {
	%>
	<div style="width: 100%;color: red;text-align: center;">
		<span>${msg}</span>
	</div>
	<%
		}
	%>




</form>

<form action="" name="pageOfficeForm" id="pageOfficeForm" style="margin: 0; padding: 0;" method="post">

	<input type="hidden" name="thPath" id="thPath"/>
	<input type="hidden" name="appid" id="appid"/>
	<input type="hidden" name="actionId" id="actionId" value="49a07aa1-81ed-4baa-aebc-83b85d63de551"/>

</form>
</body>

<script type="text/javascript">
    var ctx = "${ctx}";
    //文档是否打开
    var DocOpen = false;
    //PageOffice对象
    var PageOfficeCtrl = document.getElementById('PageOfficeCtrl');
    //文档事件
    //PageOfficeCtrl.JsFunction_BeforeDocumentSaved = "SetRevisions()";
    PageOfficeCtrl.JsFunction_AfterDocumentOpened = "SetOpenStatus()";
    PageOfficeCtrl.JsFunction_AfterDocumentClosed = "SetCloseStatus()";

    //一键套红
    function taohong(thPath,appid){
        document.getElementById("thPath").value = thPath;
        document.getElementById("appid").value = appid;
        document.getElementById("pageOfficeForm").submit();
    }

    function ApplyFileTemplate(htFilePath){
        PageOfficeCtrl.InsertDocumentFromURL(ctx+"/"+"/platform/FWFJ/FJ/1566891484414027435008/2019-08-27/aa.doc");
        PageOfficeCtrl.DataRegionList.Refresh();
        //给红头文件书签赋值
        var url = 'bindingDataRegion.jsp?method=queryFwThmbDataRegion&xh=${appid}';
        $.ajax({
            url:url,
            type:"POST",
            dataType:'json',
            async:false,
            success:function(data){
                var iCount = PageOfficeCtrl.DataRegionList.Count;
                for(var i=0; i< iCount; i++){
                    var dataRegion = PageOfficeCtrl.DataRegionList.Item(i).Name;
                    if(data.result[dataRegion]){
                        PageOfficeCtrl.DataRegionList.Item(i).value = data.result[dataRegion];
                    }
                }
            }
        });
        //  hideTemplateDiv();
    }
    //设置文档关闭
    function SetCloseStatus(){
        DocOpen = false;
    }
    //设置文档打开
    function SetOpenStatus(){
        DocOpen = true;

        //进入时默认　隐藏痕迹
        PageOfficeCtrl.ShowRevisions = false;

        try{
            //EnableFileCommand(2) = false;
            document.getElementById("PageOfficeCtrl").SetEnableFileCommand(2, false);
            document.getElementById("PageOfficeCtrl").SetEnableFileCommand(3, false); // 禁止保存
        }catch(e){}
    }
    //检测pageOffice是否已安装
    function testInstall() {
        var bInstall = false;
        try {
            if (undefined == document.getElementById("PageOfficeCtrl")) {
            }
            else {
                bInstall = true;
            }

        }
        catch (e) {
        }
        if (bInstall) {
        } else {
            Common.dialog({
                type: 'alert',
                width: '150px',
                height: '270px',
                content: '系统检测发现您的电脑尚未安装pageOffice插件，请先<a href="/sthb/fileDownloadController/downloadFile">安装pageOffice插件</a>'
            });
            return;

        }
    }
</script>

<script type="text/javascript" src="<%=request.getContextPath()%>/resources/platform/common/component/pageoffice/filepreview.js?v=${sysversion}"></script>
</html>
